<template>
  <div class="splitScreenView" style="position: relative">
    <div class="leftview" ref="leftview">
      <div
        style="
          position: absolute;
          top: 0px;
          z-index: 999;
          background-color: black;
          padding: 0px 10px;
        "
      >
        {{ leftimgname + " | " + leftimgtime }}
      </div>
    </div>
    <div class="rightview" ref="rightview">
      <div
        style="
          position: absolute;
          top: 0px;
          z-index: 999;
          background-color: black;
          padding: 0px 10px;
        "
      >
        {{ rightimgname + " | " + rightimgtime }}
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import scenejson from "@/components/common/Earth/earth/scene.json";
// import scenejson from '../earth/scene.json'

import { useEarthStore } from "@/stores/earth";
import { apiList } from '@/api/apiList';



import { loadGeojson, loadShp } from "@/hooks/earth/utils";

const earthStore = useEarthStore();

const leftview = ref();
const rightview = ref();

const initEarth = (el, scenejson) => {
  let earth = new XE.Earth(el);

  earth.xbsjFromJSON(scenejson);
  // 添加影像图层
  const layer = new Cesium.UrlTemplateImageryProvider({
    url: "/tiles/img_c/{oz}/{x}/{y}",
    customTags: {
      oz(imageProvider, x, y, level) {
        return level + 1;
      },
    },
    tileHeight: 256,
    tileWidth: 256,
    tilingScheme: new Cesium.GeographicTilingScheme({}),
  });

  let img_c = earth.sceneTree.$refs.weixing.czmObject;
  img_c.xbsjImageryProvider.UrlTemplateImageryProvider._imageryProvider = layer;
  // img_c.enabled = true

  const layer1 = new Cesium.UrlTemplateImageryProvider({
    url: "/tiles/label/{oz}/{x}/{y}",
    customTags: {
      oz(imageProvider, x, y, level) {
        return level + 1;
      },
    },
    tileHeight: 256,
    tileWidth: 256,
    tilingScheme: new Cesium.GeographicTilingScheme({}),
  });

  let label = earth.sceneTree.$refs.zhuji.czmObject;
  label.xbsjImageryProvider.UrlTemplateImageryProvider._imageryProvider = layer1;

  return earth;
};

const initHandler = (viewer0, viewer1) => {
  function viewer1sync() {
    viewer1.camera.flyTo({
      destination: viewer0.camera.position,
      orientation: {
        heading: viewer0.camera.heading,
        pitch: viewer0.camera.pitch,
        roll: viewer0.camera.roll,
      },
      duration: 0.0,
    });
  }

  function viewer0sync() {
    viewer0.camera.flyTo({
      destination: viewer1.camera.position,
      orientation: {
        heading: viewer1.camera.heading,
        pitch: viewer1.camera.pitch,
        roll: viewer1.camera.roll,
      },
      duration: 0.0,
    });
  }

  viewer0.camera.changed.addEventListener(viewer1sync);
  viewer0.scene.preRender.addEventListener(viewer1sync);

  viewer1.camera.changed.addEventListener(viewer0sync);
  viewer1.scene.preRender.addEventListener(viewer0sync);
};

const initHandler1 = (viewer0, viewer1) => {
  var _self = { handler: "", handler1: "" };
  // if (_self.handler && _self.handler.getInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)) {
  //     return;
  // }
  _self.handler = new Cesium.ScreenSpaceEventHandler(viewer0.scene.canvas);
  _self.handler1 = new Cesium.ScreenSpaceEventHandler(viewer1.scene.canvas);
  _self.handler.setInputAction(function (movement) {
    var _camerca = viewer0.camera;
    viewer1.camera.setView({
      destination: _camerca.position,
      orientation: {
        direction: _camerca._direction,
        up: _camerca.up,
        heading: _camerca.heading,
        pitch: _camerca.pitch,
        roll: _camerca.roll,
      },
    });
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  _self.handler.setInputAction(function (movement) {
    var _camerca = viewer0.camera;
    viewer1.camera.setView({
      destination: _camerca.position,
      orientation: {
        direction: _camerca._direction,
        up: _camerca.up,
        heading: _camerca.heading,
        pitch: _camerca.pitch,
        roll: _camerca.roll,
      },
    });
  }, Cesium.ScreenSpaceEventType.WHEEL);

  _self.handler1.setInputAction(function (movement) {
    var _camerca = viewer1.camera;
    viewer0.camera.setView({
      destination: _camerca.position,
      orientation: {
        direction: _camerca._direction,
        up: _camerca.up,
        heading: _camerca.heading,
        pitch: _camerca.pitch,
        roll: _camerca.roll,
      },
    });
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  _self.handler1.setInputAction(function (movement) {
    var _camerca = viewer1.camera;
    viewer0.camera.setView({
      destination: _camerca.position,
      orientation: {
        direction: _camerca._direction,
        up: _camerca.up,
        heading: _camerca.heading,
        pitch: _camerca.pitch,
        roll: _camerca.roll,
      },
    });
  }, Cesium.ScreenSpaceEventType.WHEEL);
};

let earth1 = null;
let earth2 = null;
const leftimgname = ref("");
const leftimgtime = ref("");
const rightimgname = ref("");
const rightimgtime = ref("");

const createViewer = () => {
  earth1 = initEarth(leftview.value, scenejson);
  earth2 = initEarth(rightview.value, scenejson);
  // 同步视图
  // initHandler(earth1.czm.viewer, earth2.czm.viewer);
  initHandler1(earth1.czm.viewer, earth2.czm.viewer);
  // 添加 对应图层
  let type = earthStore.pannellist["splitpannel"].options.type;
  let data = earthStore.pannellist["splitpannel"].options.data;
  console.log(type, data);

  // let resgeojsonentity = loadGeojson(data)
  // resgeojsonentity.map(item => {
  //   earth1.czm.viewer.entities.add(item)
  //   earth2.czm.viewer.entities.add(item)
  // })

  let imgindex = 0;

  let imglist = data.data_path.split(";")
  imglist.map((item) => {
    // if (item.type == "tif") {
      //添加图层
      let filename = item.split("\\").pop()
      let tmpname = filename.split(".")
      tmpname.pop()
      let name = tmpname.join(".");
      if (imgindex == 0) {

        apiList.genWmsService({file:item, filename: filename}).then(res =>{
          let basemapSource = new Cesium.WebMapTileServiceImageryProvider({
        //  对与url  很多博客都说要进行 如下拼接
        // 后端返回的wmts/rest/{layer}/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png
        // 其实不用拼接  只需要后端返回的/wtms路径即可
        url: '/geoserver/gwc/service/wmts', //服务地址 服务地址只需要后端返回的 /WMTS   不需要给后面拼接任何东西，  
        layer: `test_tif:${name}`, //图层名称 : "pucheng:satellite"
        style: '',
        format: 'image/png',
        tileMatrixSetID: 'EPSG:4326',  // "EPSG:900913"
        // 地图飞入  定位的坐标  后端返回的数据
        // rectangle: Cesium.Rectangle.fromDegrees(
        //     +this.zb.xmin, +this.zb.ymin, +this.zb.xmax, +this.zb.ymax),
        // 必须加  不然地图出不来
        //之所以要在这里提出这个tileMatrixLabels参数，是因为GeoServer在缓冲切分瓦片时对每一个缩放级别的存储目录没有使用相应的数字，而使用了网格+级别的方式来命名，如“EPSG:9100913:10”表示的是使用“EPSG:9100913”网格切分的第10级瓦片。
        tileMatrixLabels : [`${'EPSG:4326'}:0`,`${'EPSG:4326'}:1`, `${'EPSG:4326'}:2`,`${'EPSG:4326'}:3`,`${'EPSG:4326'}:4`,`${'EPSG:4326'}:5`,`${'EPSG:4326'}:6`,
        `${'EPSG:4326'}:7`,`${'EPSG:4326'}:8`,`${'EPSG:4326'}:9`,`${'EPSG:4326'}:10`,`${'EPSG:4326'}:11`,`${'EPSG:4326'}:12`,`${'EPSG:4326'}:13`,`${'EPSG:4326'}:14`,
        `${'EPSG:4326'}:15`,`${'EPSG:4326'}:16`,`${'EPSG:4326'}:17`,`${'EPSG:4326'}:18`,
        ],
        // 必须加  不然地图出不来
        tilingScheme: new Cesium.GeographicTilingScheme({//此处很重要，很重要。。。
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 1
        }),
        // tilematrixset: 'EPSG:4326',
        // maximumLevel: 18,
      });
          earth1.czm.viewer.imageryLayers.addImageryProvider(basemapSource);
          
        })


        leftimgname.value = name;
        // leftimgtime.value = item.created_time;
        imgindex++;
      } else if (imgindex == 1) {
        
        apiList.genWmsService({file:item, filename: filename}).then(res =>{
          let basemapSource = new Cesium.WebMapTileServiceImageryProvider({
        //  对与url  很多博客都说要进行 如下拼接
        // 后端返回的wmts/rest/{layer}/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png
        // 其实不用拼接  只需要后端返回的/wtms路径即可
        url: '/geoserver/gwc/service/wmts', //服务地址 服务地址只需要后端返回的 /WMTS   不需要给后面拼接任何东西，  
        layer: `test_tif:${name}`, //图层名称 : "pucheng:satellite"
        style: '',
        format: 'image/png',
        tileMatrixSetID: 'EPSG:4326',  // "EPSG:900913"
        // 地图飞入  定位的坐标  后端返回的数据
        // rectangle: Cesium.Rectangle.fromDegrees(
        //     +this.zb.xmin, +this.zb.ymin, +this.zb.xmax, +this.zb.ymax),
        // 必须加  不然地图出不来
        //之所以要在这里提出这个tileMatrixLabels参数，是因为GeoServer在缓冲切分瓦片时对每一个缩放级别的存储目录没有使用相应的数字，而使用了网格+级别的方式来命名，如“EPSG:9100913:10”表示的是使用“EPSG:9100913”网格切分的第10级瓦片。
        tileMatrixLabels : [`${'EPSG:4326'}:0`,`${'EPSG:4326'}:1`, `${'EPSG:4326'}:2`,`${'EPSG:4326'}:3`,`${'EPSG:4326'}:4`,`${'EPSG:4326'}:5`,`${'EPSG:4326'}:6`,
        `${'EPSG:4326'}:7`,`${'EPSG:4326'}:8`,`${'EPSG:4326'}:9`,`${'EPSG:4326'}:10`,`${'EPSG:4326'}:11`,`${'EPSG:4326'}:12`,`${'EPSG:4326'}:13`,`${'EPSG:4326'}:14`,
        `${'EPSG:4326'}:15`,`${'EPSG:4326'}:16`,`${'EPSG:4326'}:17`,`${'EPSG:4326'}:18`,
        ],
        // 必须加  不然地图出不来
        tilingScheme: new Cesium.GeographicTilingScheme({//此处很重要，很重要。。。
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 1
        }),
        // tilematrixset: 'EPSG:4326',
        // maximumLevel: 18,
      });
          earth2.czm.viewer.imageryLayers.addImageryProvider(basemapSource);
          
        })
        
        
        rightimgname.value = name;
        imgindex++;
        console.log(rightimgname.value);
        // rightimgtime.value = item.created_time;
      }
    // }
  });
  // if (item.type == "shp") {
    // 添加矢量
    let shplist = data.shp_path.split(";")
    shplist.map((item) => {

      //判断添加到左边还是右边

      if (item.indexOf("left") != -1 && item.indexOf("no") == -1) {
        loadShp(item, 25000, ["QMC", "BHLX"]).then((res) => {
          earth2.czm.viewer.dataSources.add(res);
          earth2.czm.viewer.flyTo(res.entities.values, {
            offset: new Cesium.HeadingPitchRange(0, -1.7, 10000),
            duration: 0.2,
          });
        });
      }else if(item.indexOf("right") != -1){
        // loadShp(item, 25000, ["QMC", "BHLX"]).then((res) => {
        //   earth1.czm.viewer.dataSources.add(res);
        //   earth1.czm.viewer.flyTo(res.entities.values, {
        //     offset: new Cesium.HeadingPitchRange(0, -1.7, 10000),
        //     duration: 0.2,
        //   });
        // });
      }
    })
    // loadShp(item).then((res) => {
    //   earth1.czm.viewer.dataSources.add(res);
    //   earth1.czm.viewer.flyTo(res.entities.values, {
    //     offset: new Cesium.HeadingPitchRange(0, -1.7, 10000),
    //     duration: 0.2,
    //   });
    // });
  // }

  //添加点击交互事件     // 后续添加
  // let handler = new Cesium.ScreenSpaceEventHandler(earth2.czm.viewer.scene.canvas);
  // handler.setInputAction(function (movement) {
  //   let e = earth2.czm.viewer.scene.pick(movement.position)
  //   if (e != undefined) {
  //     console.log(e);
  //     earth1.czm.viewer.entities.add(e.id);
  //     setTimeout(() => {
  //       earth1.czm.viewer.entities.remove(e.id);
  //     }, 1000);
  //   }
  // }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

};

const startup = () => {
  if (XE.isReady()) {
    createViewer();
  } else {
    XE.ready()
      .then(() => {
        // 加载标绘插件
        const p1 = XE.HTML.loadJS(
          "/earthsdk/XbsjEarth-Plugins/plottingSymbol/plottingSymbol.js"
        );

        const p2 = XE.HTML.loadJS(
          "/earthsdk/XbsjEarth-Plugins/customPrimitive/customPrimitive.js"
        );

        const p3 = XE.HTML.loadJS(
          "/earthsdk/XbsjEarth-Plugins/customPrimitiveImage/customPrimitiveImage.js"
        );

        const p4 = XE.HTML.loadJS("/earthsdk/scripts/three.min.js"); // 部分图元需要加载three.js

        const p5 = XE.HTML.loadJS(
          "/earthsdk/XbsjEarth-Plugins/plottingSymbol2/plottingSymbol2.js"
        );
        return Promise.all([p1, p2, p3, , p4, p5]);
      })
      .then(() => {
        createViewer();
      });
  }
};

onMounted(() => {
  startup();
});

onUnmounted(() => {
  earth1.destroy();
  earth2.destroy();
});
</script>
<style lang="scss" scoped>
.leftview {
  width: 50%;
  height: 100%;
}

.rightview {
  width: 50%;
  height: 100%;
}

.splitScreenView {
  display: flex;
  width: 100%;
  height: 100%;
}
</style>
